﻿using SharpSoft.WPF;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ResetIdle
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.Loaded += MainWindow_Loaded;
            timer.Interval = TimeSpan.FromSeconds(60);
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {

            check();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            e.Cancel = true;
            this.Visibility = Visibility.Collapsed;
            this.ShowInTaskbar = false;
        }

        private void check()
        {
            if (listenIds == null)
            {
                return;
            }
            var ps = System.Diagnostics.Process.GetProcesses();
            foreach (var p in ps)
            {
                if (listenIds.Contains(p.ProcessName))
                {
                    WindowsHelper.ResetIdle(true);
                    return;
                }
            }
        }

        System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();


        public System.Diagnostics.Process[] Processes
        {
            get { return (System.Diagnostics.Process[])GetValue(ProcessesProperty); }
            set { SetValue(ProcessesProperty, value); }
        }

        public static readonly DependencyProperty ProcessesProperty =
            DependencyProperty.Register("Processes", typeof(System.Diagnostics.Process[]), typeof(MainWindow), new PropertyMetadata(null));




        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            LoadConfigFile();
            var ps = System.Diagnostics.Process.GetProcesses();
            List<System.Diagnostics.Process> list = new List<System.Diagnostics.Process>();
            foreach (var p in ps)
            {
                if (p.MainWindowHandle != IntPtr.Zero)
                {

                    try
                    {
                        if (p.MainModule != null)
                        {
                            if (!string.IsNullOrWhiteSpace(p.MainModule.FileVersionInfo.FileDescription))
                            {
                                list.Add(p);
                            }

                        }
                    }
                    catch (Exception)
                    {

                    }
                }

            }
            Processes = list.ToArray();
        }

        private List<string> listenIds = new List<string>();

        private void SaveConfigFile()
        {
            var f = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var folder = System.IO.Path.Combine(f, "ResetIdle");
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }
            using (var fs = new FileStream(System.IO.Path.Combine(folder, "cfg.txt"), FileMode.Create))
            {
                using (var sr = new StreamWriter(fs, Encoding.UTF8))
                {
                    if (listenIds != null)
                    {
                        var content = string.Join(",", listenIds);
                        sr.Write(content);
                    }

                }
            }
        }

        private void LoadConfigFile()
        {
            var f = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            var folder = System.IO.Path.Combine(f, "ResetIdle");
            if (!System.IO.Directory.Exists(folder))
            {
                System.IO.Directory.CreateDirectory(folder);
            }
            var file = System.IO.Path.Combine(folder, "cfg.txt");
            if (File.Exists(file))
            {
                using (var fs = new FileStream(file, FileMode.Open))
                {
                    using (var sr = new StreamReader(fs, Encoding.UTF8))
                    {
                        if (listenIds != null)
                        {
                            var txt = sr.ReadToEnd();
                            var txts = txt.Split(',');
                            List<string> list = new List<string>();
                            foreach (var item in txts)
                            {
                                list.Add(item);
                            }
                            listenIds = list;
                            foreach (var item in listenIds)
                            { 
                                llist.Items.Add(item);
                            }
                        }

                    }
                }
            }

        }

        private void btn_remove_Click(object sender, RoutedEventArgs e)
        {
            if (llist.SelectedValue is string pname)
            {
                llist.Items.Remove(pname);
                if (listenIds.Contains(pname))
                {
                    listenIds.Remove(pname);
                }
            }

            SaveConfigFile();
        }

        private void btn_add_Click(object sender, RoutedEventArgs e)
        {
            if (plist.SelectedValue is System.Diagnostics.Process p)
            {
                if (!listenIds.Contains(p.ProcessName))
                {
                    listenIds.Add(p.ProcessName);
                    llist.Items.Add(p.ProcessName);
                }
            }

            SaveConfigFile();
        }
    }
}
